package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.Folder;
import util.DBHelp;
import util.RowMapper;

public class FolderDao {
		
	private DBHelp<Folder> db = new DBHelp<Folder>();
	
	public int addFolder(Folder folder){
		String sql = "insert into bmw_folder (name , bmw_project_id, bmw_user_id) value(?,?,?)";
		return db.excuteSQL(sql, folder.getName(), folder.getProjectId(), folder.getUserId());
	}
	
	public int delFolder(int id){
		String sql = "delete from bmw_folder where id = ?";
		return db.excuteSQL(sql, id);
	}
	
	public List<Folder> findByprojectId(int projectId){
		String sql = "SELECT bmw_folder.id, bmw_folder.name, bmw_project_id, bmw_folder.bmw_user_id, bmw_user.name AS bmw_user_name, (SELECT COUNT(bmw_file.id) FROM bmw_file WHERE bmw_file.bmw_folder_id = bmw_folder.id) AS fileNum, (SELECT SUM(bmw_file.size) FROM bmw_file WHERE bmw_file.bmw_folder_id = bmw_folder.id) AS totalSize FROM bmw_folder,bmw_user WHERE bmw_folder.bmw_user_id = bmw_user.id AND bmw_project_id = ? ";
		return db.excuteForList(sql, new FolderRowMapper(), projectId);
	}
	
	public Folder findById(int id) {
	    String sql = "select * from bmw_folder where id = ?";
	    return db.executeForObject(sql, new FoldersRowMapper(), id);
	}
	
	private class FolderRowMapper implements RowMapper<Folder>{

		@Override
		public Folder mapperRow(ResultSet rs) throws SQLException {
			Folder folder = new Folder();
			folder.setId(rs.getInt("id"));
			folder.setName(rs.getString("name"));
			folder.setProjectId(rs.getInt("bmw_project_id"));
			folder.setUserId(rs.getInt("bmw_user_id"));
			folder.setUserName(rs.getString("bmw_user_name"));
			folder.setTotalSize(rs.getLong("totalSize"));
			folder.setFileNum(rs.getInt("fileNum"));
			return folder;
		}
		
	}
	private class FoldersRowMapper implements RowMapper<Folder>{

		@Override
		public Folder mapperRow(ResultSet rs) throws SQLException {
			Folder folder = new Folder();
			folder.setId(rs.getInt("id"));
			folder.setName(rs.getString("name"));
			folder.setProjectId(rs.getInt("bmw_project_id"));
			folder.setUserId(rs.getInt("bmw_user_id"));
			return folder;
		}
		
	}
}
